package com.apes.enquiry.supplier;

import afu.org.checkerframework.checker.oigj.qual.O;
import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.SpringManager;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.esb.processor.connector.http.HttpTransporter;
import com.apes.framework.rop.converter.DateUtils;
import com.apes.framework.util.DateUtil;
import com.apes.framework.util.NetUtil;
import com.apes.framework.util.statistics.Statistics;
import com.apes.framework.util.statistics.StatisticsRepository;
import com.apestech.framework.json.JSON;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public abstract class SupplierInterfaceApi implements SupplierInterface{

    public JSONObject executeGet(String url, Map content, Map header){
        return execute(url, content, header, "GET");
    }

    public JSONObject executePost(String url, Map content, Map header) {
        return execute(url, content, header, "POST");
    }

    @Override
    public JSONObject execute(String url, Map content, Map header, String method) {
        String beginData = DateUtil.format(new Date(), DateUtils.SHOW_DATETIME_FORMAT);
        // 添加头部信息
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        if (header != null) headers.putAll(header);

        HttpTransporter transporter = new HttpTransporter();
        transporter.setUrl(url);
        transporter.setHeaders(headers);
        transporter.setAction(method);
        try {
            SimpleRequest request = new SimpleRequest();
            request.setData("GET".equals(method)?content:JSON.toJSONString(new JSONObject(content)));
            JSONObject obj = JSONObject.parseObject((String) transporter.process(request));  // 调用

            // 写入日志
            this.writeLog(beginData, url, content, obj);

            return obj;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // 写日志
    private void writeLog(String beginData, String method, Map content, JSONObject reponse) {
        Statistics statistics = new Statistics();
        statistics.setMethod(method);
        statistics.setRequest(new JSONObject(content).toJSONString());
        statistics.setResponse(reponse.toJSONString());
        statistics.setServer(NetUtil.getServerIp());
        statistics.setEndTime(DateUtil.format(new Date(), DateUtils.SHOW_DATETIME_FORMAT));
        SpringManager.getBean(StatisticsRepository.class).save(statistics);
    }

}
